package com.fengxu.netty.codec2;

import com.fengxu.netty.codec.StudentPOJO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

// 客户端管道处理器
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    // 当通道就绪时触发的事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int rand = new Random().nextInt(2);
        MyDataInfo.MyMessage myMessag = null;
        if(rand == 0){
            myMessag = MyDataInfo.MyMessage.newBuilder()
                    .setDataType(MyDataInfo.MyMessage.DataType.StudentType)
                    .setStudent(MyDataInfo.Student.newBuilder().setId(1).setName("ojj").build())
                    .build();
        } else {
            myMessag = MyDataInfo.MyMessage.newBuilder()
                    .setDataType(MyDataInfo.MyMessage.DataType.WorkerType)
                    .setWorker(MyDataInfo.Worker.newBuilder().setName("ojj").setAge(1).build())
                    .build();
        }
        ctx.writeAndFlush(myMessag);
    }

    // 通道可读事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到服务器的消息:"+byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器地址:"+ctx.channel().remoteAddress().toString().substring(1));
    }
}
